<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型编码" prop="modelCode">
        <el-input
          v-model="queryParams.modelCode"
          placeholder="请输入模型编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"/>
      <el-table-column label="模型编码" align="center" prop="modelCode" width="130" show-overflow-tooltip />
      <el-table-column label="模型名称" align="center" prop="modelName" width="130" show-overflow-tooltip />
      <el-table-column label="算法名称" align="center" prop="algorithmName" width="130" show-overflow-tooltip />
      <el-table-column label="模型作者" align="center" prop="modelAuthor" />
      <el-table-column label="训练耗时" align="center" prop="trainDuration" width="150">
        <template slot-scope="scope">
          <span>{{ parseTimeMillis(scope.row.trainDuration) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调用次数" align="center" prop="callCount" />
      <el-table-column label="调用时间" align="center" prop="callTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.callTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模型版本" align="center" prop="modelVersion" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改X光模型管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="128px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模型编码" prop="modelCode">
              <el-input v-model="form.modelCode" placeholder="请输入模型编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="form.modelName" placeholder="请输入模型名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模型作者" prop="modelAuthor">
              <el-input v-model="form.modelAuthor" placeholder="请输入模型作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Python算法" prop="algorithmId">
              <el-select v-model="form.algorithmId" placeholder="请选择算法" style="width: 100%" @change="handleAlgorithm">
                <el-option
                  v-for="algorithm in algorithmList"
                  :key="algorithm.algorithmId"
                  :label="algorithm.algorithmName + ' -v' + algorithm.algorithmVersion"
                  :value="algorithm.algorithmId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="modelParam">
              <span slot="label">
                <el-tooltip content="输入模型参数，如 --weights" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                模型参数
              </span>
              <el-input v-model="form.modelParam" placeholder="请输入模型参数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入模型文件名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传模型文件" prop="absolutePath">
              <file-upload :limit="1" :file-type="['pt']" @multipleInput="getModelUpload" :file-size="320" :is-show-file-list="false" :open-time="new Date().getTime()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="configParam">
              <span slot="label">
                <el-tooltip content="输入模型配置参数，如 --data" placement="top">
                <i class="el-icon-question"></i>
                </el-tooltip>
                模型配置参数
              </span>
              <el-input v-model="form.configParam" placeholder="请输入模型配置参数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入模型配置名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传模型配置" prop="configAbsolutePath">
              <file-upload :limit="1" :file-type="['yaml']" @multipleInput="getConfigUpload" :is-show-file-list="false" :open-time="new Date().getTime()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="训练开始时间" prop="startTime">
              <el-date-picker clearable
                              v-model="form.startTime"
                              type="datetime"
                              style="width: 100%"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择训练开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="训练结束时间" prop="endTime">
              <el-date-picker clearable
                              v-model="form.endTime"
                              type="datetime"
                              style="width: 100%"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择训练结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="255" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listModel, getModel, delModel, addModel, updateModel } from "@/api/algorithm/model";
import { listAlgorithmData } from '@/api/system/algorithm'

export default {
  name: "Model",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // X光模型管理表格数据
      modelList: [],
      // Python算法表格数据
      algorithmList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelCode: null,
        modelName: null,
        modelAuthor: null,
        modelParam: null,
        fileName: null,
        absolutePath: null,
        configParam: null,
        configName: null,
        configAbsolutePath: null,
        startTime: null,
        endTime: null,
        trainDuration: null,
        callCount: null,
        callTime: null,
        modelVersion: null,
        algorithmId: null,
        algorithmCode: null,
        algorithmName: null,
        algorithmType: 'x_ray',
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelCode: [
          { required: true, message: "模型编码不能为空", trigger: "blur" }
        ],
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        modelAuthor: [
          { required: true, message: "模型作者不能为空", trigger: "blur" }
        ],
        modelParam: [
          { required: true, message: "模型参数不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: true, message: "模型文件名称不能为空", trigger: "blur" }
        ],
        configParam: [
          { required: true, message: "模型配置参数不能为空", trigger: "blur" }
        ],
        configName: [
          { required: true, message: "模型配置名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "训练开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "训练结束时间不能为空", trigger: "blur" }
        ],
        algorithmId: [
          { required: true, message: "算法不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询X光模型管理列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelCode: null,
        modelName: null,
        modelAuthor: null,
        modelParam: '--weights',
        fileName: null,
        absolutePath: null,
        configParam: '--data',
        configName: null,
        configAbsolutePath: null,
        startTime: null,
        endTime: null,
        trainDuration: null,
        callCount: null,
        callTime: null,
        modelVersion: null,
        algorithmId: null,
        algorithmCode: null,
        algorithmName: null,
        algorithmType: 'x_ray',
        delFlag: null,
        status: '0',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getAlgorithmList() {
      listAlgorithmData({algorithmType: 'x_ray', status: '0'}).then(res => {
        this.algorithmList = res.data
      })
    },
    handleAlgorithm(val) {
      if (val) {
        this.algorithmList.forEach(item => {
          if (item.algorithmId === val) {
            this.form.algorithmCode = item.algorithmCode
            this.form.algorithmName = item.algorithmName
            this.form.algorithmType = item.algorithmType
          }
        })
      }
    },
    getModelUpload(res) {
      if (res.length > 0) {
        let file = res[0]
        this.form.fileName = file.originalFilename
        this.form.absolutePath = file.absolutePath
      }
    },
    getConfigUpload(res) {
      if (res.length > 0) {
        let file = res[0]
        this.form.configName = file.originalFilename
        this.form.configAbsolutePath = file.absolutePath
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAlgorithmList()
      this.open = true;
      this.title = "添加X光模型管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getAlgorithmList()
      const modelId = row.modelId || this.ids
      getModel(modelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改X光模型管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.modelId != null) {
            updateModel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$modal.confirm('是否确认删除X光模型管理编号为"' + modelIds + '"的数据项？').then(function() {
        return delModel(modelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('algorithm/model/export', {
        ...this.queryParams
      }, `model_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
